package com.wxy.demo.mqtt;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 发布
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/7/25 15:53
 */
@Slf4j
public class PublishDemo {
    public static void main(String[] args) throws MqttException, InterruptedException {
        // 连接配置
        String broker = "tcp://localhost:1883";
        String username = "admin";
        String password = "admin";
        String clientId = "publish";
        boolean cleanSession = true;
        // 发布配置
        String topic = "test";
        String content = "hello";
        int qos = 1;
        boolean retained = false;
        // 创建客户端
        MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());
        // 创建链接参数
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(cleanSession);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        // 建立连接
        client.connect(options);
        // 创建消息
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        message.setRetained(retained);
        client.publish(topic, message);
        // 发布消息
        log.info("发布消息：topic = {}，message = {}", topic, message);
        // 关闭连接
//        client.disconnect();
//        client.close();
        client.disconnectForcibly(500);
        client.close(true);
    }
}
